package com.mooc.ppjoke.ui;

import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import androidx.paging.DataSource;
import androidx.paging.LivePagedListBuilder;
import androidx.paging.PagedList;

import org.jetbrains.annotations.NotNull;

/**
 * @ClassName: AbsViewModel$
 * @Description: java类作用描述
 * @Author: 魏靳元
 * @CreateDate: 2022/8/18 15:35
 * @UpdateRemark: 更新内容
 * @Version: 1.0
 */
public abstract class AbsViewModel<T> extends ViewModel {

    protected PagedList.Config config;
    private LiveData<PagedList<T>> liveData;
    private DataSource dataSource;
    private MutableLiveData<Boolean> boundaryLiveData=new MutableLiveData<>();
    public AbsViewModel(){
        config = new PagedList.Config.Builder()
                .setPageSize(10)
                .setInitialLoadSizeHint(12)
                // .setMaxSize(100)；最大数据长度
                // .setEnablePlaceholders(false)//占位符
                // .setPrefetchDistance() 设置的pagesize为10 距底部剩10个item进行加载更多
                .build();
        liveData = new LivePagedListBuilder(factory, config)
                .setInitialLoadKey(0)
//                .setFetchExecutor()
                .setBoundaryCallback(callback)//数据加载状态
                .build();

    }
    public LiveData<PagedList<T>> getLiveData(){
        return liveData;
    }

    public DataSource getDataSource(){
        return dataSource;
    }
    public LiveData<Boolean> getBoundaryLiveData(){
        return boundaryLiveData;
    }

    PagedList.BoundaryCallback<T> callback=new PagedList.BoundaryCallback<T>() {
        @Override
        public void onZeroItemsLoaded() {
            boundaryLiveData.postValue(false);
        }

        @Override
        public void onItemAtFrontLoaded(@NonNull @NotNull Object itemAtFront) {
            boundaryLiveData.postValue(true);
        }

        @Override
        public void onItemAtEndLoaded(@NonNull @NotNull Object itemAtEnd) {
        }
    };


    DataSource.Factory factory=new DataSource.Factory() {
        @NonNull
        @NotNull
        @Override
        public DataSource create() {
            if(dataSource==null||dataSource.isInvalid()){
                dataSource = createDataSource();
            }
            return dataSource;
        }
    };
    public abstract DataSource createDataSource();
} 
